import React, { useEffect, useRef } from 'react';
import PropTypes from 'prop-types';
import { Button, DatePicker, Empty, Form, Icon, Input, Select, Typography, message } from 'antd';
import { useRequest } from '@/hooks';
import useDynamicList from '@/hooks/useDynamicList';
import moment from 'moment';
import useDictionary from '@/hooks/useDictionary';
import { formatDateRange } from '@/utils/utils';
import FormContainer from './FormContainer';

const { Text } = Typography;

const RANGE_PICKER_FORMAT_YYYY_MM_DD = 'YYYY-MM-DD';

/**
 * 员工档案 - 教育经历
 */
const EducationalExperienceSection = ({ formData, onChange, readonly, saveAction, ...props }) => {
    const formRef = useRef();
    // 提交
    const { run: submitRun } = useRequest(submitData => saveAction && saveAction(submitData), {
        manual: true
    });
    // 字典数据
    const [academicYearList, getAcademicYearText] = useDictionary('academicYear');
    const [degreeTypeList, getDegreeTypeText] = useDictionary('agreeType');
    const [educationTypeList, getEducationTypeText] = useDictionary('degreeType');
    // 列表管理
    const {
        list: eduList,
        remove: eduListRemove,
        push: eduListPush,
        getKey: eduListGetKey,
        resetList: eduListReset
    } = useDynamicList([]);

    useEffect(() => {
        // 重置列表的值
        eduListReset(formData.eduList);
    }, [eduListReset, formData.eduList]);

    useEffect(() => {
        // 表单赋值
        formRef.current.getFieldDecorator('eduList', { initialValue: formData.eduList || [] });
    }, [formData.eduList]);

    // 保存
    const handleSubmit = async values => {
        const submitData = Object.assign({
            entryPersonnelCode: formData.entryPersonnelCode,
            newList: eduList.map((item, index) => {
                const key = eduListGetKey(index);
                return {
                    startTime: values.startTime[key][0]?.format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    endTime: values.startTime[key][1]?.format(RANGE_PICKER_FORMAT_YYYY_MM_DD),
                    graduateSchool: values.graduateSchool[key],
                    major: values.major[key],
                    certificate: values.certificate[key],
                    academicYear: values.academicYear[key],
                    degree: values.degree[key]
                };
            })
        });
        // 提交
        const res = await submitRun(submitData);
        if (res.code === 10000) {
            message.success(res.msg);
            onChange(submitData.newList);
        } else {
            message.error(res.msg);
        }
    };

    // 取消编辑
    const handleCancel = () => {
        eduListReset(formData.eduList);
    };

    // 处理日期为空的情况
    const preprocessDateRange = (startDate, endDate) => [startDate && moment(startDate), endDate && moment(endDate)];

    // 很奇怪, 日期选择组件不能自动赋值
    const handleSetStartTimeValue = (values, keys) => {
        formRef.current.setFieldsValue({ [keys]: values });
    };

    // 取消编辑
    const handleEdit = () => {
        if (eduList.length === 0) {
            eduListPush({});
        }
    };

    // render
    return (
        <FormContainer
            ref={formRef}
            title="教育经历"
            hasEditAuth={!readonly && !!saveAction}
            onSubmit={handleSubmit}
            onCancel={handleCancel}
            onEdit={handleEdit}
            {...props}
        >
            {({ getFieldDecorator }, editStatus) => (
                <div className="dynamicList">
                    {eduList.length === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
                    <div className="dynamicListContainer">
                        {eduList.map((item, index) => (
                            <div key={eduListGetKey(index)} className="dynamicListItem">
                                {editStatus && props.isEntryGuide && (
                                    <div className="dynamicListItemHeader">教育经历 {index + 1}</div>
                                )}
                                {editStatus && (
                                    <Icon
                                        onClick={() => eduListRemove(index)}
                                        className="dynamicListClose"
                                        type="close-circle"
                                        theme="filled"
                                    />
                                )}
                                <Form.Item label="起止时间">
                                    {editStatus
                                        ? getFieldDecorator(`startTime[${eduListGetKey(index)}]`, {
                                              initialValue: item?.startTime
                                              ? preprocessDateRange(item?.startTime, item?.endTime) : undefined,
                                              rules: [{ required: true, message: '起止时间不能为空' }]
                                          })(
                                              <DatePicker.RangePicker
                                                  format={RANGE_PICKER_FORMAT_YYYY_MM_DD}
                                                  style={{ width: '100%' }}
                                                  onPanelChange={values =>
                                                      handleSetStartTimeValue(
                                                          values,
                                                          `startTime[${eduListGetKey(index)}]`
                                                      )
                                                  }
                                              />
                                          )
                                        : formatDateRange(item?.startTime, item?.endTime, 'YYYY-MM-DD') || '--'}
                                </Form.Item>
                                <Form.Item label="学校名称">
                                    {editStatus ? (
                                        getFieldDecorator(`graduateSchool[${eduListGetKey(index)}]`, {
                                            initialValue: item?.graduateSchool ?? undefined,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入学校名称'
                                                },
                                                {
                                                    min: 1,
                                                    max: 50,
                                                    message: '请输入1~50个字符'
                                                },
                                                {
                                                    pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                    message: '此处不能输入空格'
                                                }
                                            ]
                                        })(<Input placeholder="请输入" />)
                                    ) : (
                                        <div className="multiLineText">{item?.graduateSchool || '--'}</div>
                                    )}
                                </Form.Item>
                                <Form.Item label="专业">
                                    {editStatus ? (
                                        getFieldDecorator(`major[${eduListGetKey(index)}]`, {
                                            initialValue: item?.major ?? undefined,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入专业名称'
                                                },
                                                {
                                                    min: 1,
                                                    max: 50,
                                                    message: '请输入1~50个字符'
                                                },
                                                {
                                                    pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                    message: '此处不能输入空格'
                                                }
                                            ]
                                        })(<Input placeholder="请输入" />)
                                    ) : (
                                        <div className="multiLineText">{item?.major || '--'}</div>
                                    )}
                                </Form.Item>

                                <Form.Item label="学制">
                                    {editStatus ? (
                                        getFieldDecorator(`academicYear[${eduListGetKey(index)}]`, {
                                            initialValue: item?.academicYear !== '' ? item?.academicYear : undefined,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请选择学制'
                                                },
                                                {
                                                    pattern: /^[^\s]+(\s+[^\s]+)*$/,
                                                    message: '此处不能输入空格'
                                                }
                                            ]
                                        })(
                                            <Select
                                                getPopupContainer={trigger => trigger.parentElement}
                                                placeholder="请选择"
                                            >
                                                {academicYearList?.map(option => (
                                                    <Select.Option value={option?.value} key={option?.value}>
                                                        {option?.text}
                                                    </Select.Option>
                                                ))}
                                            </Select>
                                        )
                                    ) : (
                                        <Text>{getAcademicYearText(item?.academicYear) || '--'}</Text>
                                    )}
                                </Form.Item>
                                <Form.Item label="学位">
                                    {editStatus ? (
                                        getFieldDecorator(`certificate[${eduListGetKey(index)}]`, {
                                            initialValue: item?.certificate !== '' ? item?.certificate : undefined
                                        })(
                                            <Select
                                                getPopupContainer={trigger => trigger.parentElement}
                                                placeholder="请选择"
                                            >
                                                {educationTypeList?.map(option => (
                                                    <Select.Option value={option.value} key={option?.value}>
                                                        {option?.text}
                                                    </Select.Option>
                                                ))}
                                            </Select>
                                        )
                                    ) : (
                                        <Text>{getEducationTypeText(item?.certificate || '--')}</Text>
                                    )}
                                </Form.Item>
                                <Form.Item label="学历">
                                    {editStatus ? (
                                        getFieldDecorator(`degree[${eduListGetKey(index)}]`, {
                                            initialValue: item?.degree !== '' ? item?.degree : undefined,
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请选择学历类型'
                                                }
                                            ]
                                        })(
                                            <Select
                                                getPopupContainer={trigger => trigger.parentElement}
                                                placeholder="请选择"
                                            >
                                                {degreeTypeList?.filter(v => v.remark !== '1')?.map(option => (
                                                    <Select.Option value={option.value} key={option?.value}>
                                                        {option?.text}
                                                    </Select.Option>
                                                ))}
                                            </Select>
                                        )
                                    ) : (
                                        <Text>{getDegreeTypeText(item?.degree || '--')}</Text>
                                    )}
                                </Form.Item>
                            </div>
                        ))}
                    </div>
                    {editStatus ? (
                        <Button className="dynamicListAddButton" block onClick={() => eduListPush({})}>
                            +添加教育经历
                        </Button>
                    ) : null}
                </div>
            )}
        </FormContainer>
    );
};

// prop
EducationalExperienceSection.propTypes = {
    formData: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    saveAction: PropTypes.func,
    readonly: PropTypes.bool
};

EducationalExperienceSection.defaultProps = {
    saveAction: null,
    readonly: false
};

export default EducationalExperienceSection;
